package com.epcs.service;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;

import org.codehaus.jettison.json.JSONObject;

import com.epcs.model.bo.EventBO;
import com.epcs.model.bo.SynchronizationBO;
import com.epcs.model.bo.UserBO;
import com.epcs.model.dto.Account;
import com.epcs.model.dto.android.AndroidEventList;
import com.google.gson.Gson;

@Path("android")
public class AndroidService {

	@Path("/auth")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public String checkLogin (String user_info){
		
		try {
			
			JSONObject obj = new JSONObject(user_info);
			String username = (String) obj.get("username");
			String password = (String) obj.get("password");
						
			Account account = new UserBO().checkLogin(username, password);
			
			if (account != null){
				return "accepted";
			} else {
				return "invalid";
			}
			
			
		} catch (Exception e) {
			System.out.println("error: " + e.getMessage());
			return "error";
		}
	}
	
	@Path("/events")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public String getAllEvents (String data){
		
		try {
			JSONObject input = new JSONObject(data);
			
			String username = input.getString("username");
			
			Account account = new UserBO().getAccountByUsername(username);
			if (account != null){
				AndroidEventList list = new EventBO().getAllEventForAndroid(account);
				
				Gson gson = new Gson();
				
				return gson.toJson(list);
			} else {
				return "invalid";
			}
			
		} catch (Exception e) {
			System.out.println("error: " + e.getMessage());
			e.printStackTrace();
			return "error";
		}
	}
	
	@Path("/sync/{username}")
	@PUT
	@Consumes(MediaType.APPLICATION_JSON)
	public String syncAllEvents (AndroidEventList androidEventList, @PathParam(value="username") String username){
		
		try {
			Gson gson = new Gson();
			System.out.println("androidEventList = " + gson.toJson(androidEventList));
			androidEventList = new SynchronizationBO().androidSync(androidEventList, username);
			
			System.out.println("(after)androidEventList = " + gson.toJson(androidEventList));
			return gson.toJson(androidEventList);
			
		} catch (Exception e) { 
			System.out.println("error: " + e.getMessage());
			e.printStackTrace();
			return "error";
		}
	}
	
	
}
